package com.zhuangjie.security.helper;

import org.springframework.http.HttpStatus;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * 无法处理的请求响应
 *
 * @author zhuangjie
 * @date 2024/03/20
 */
public class UnprocessableResponse {

    private static void responseCodeAndMessage(int code, String message) throws IOException {

        // 获取response
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();

        // 1. 设置状态码为401
        response.setStatus(code);
        if (message == null) return;
        // 2. 设置响应头
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        // 3. 设置响应体
        PrintWriter writer = response.getWriter();
        writer.write("{\"message\":\"" + message + "\"}");
        writer.flush();
        writer.close();

    }

    /**
     * 响应 401
     * @param message
     * @throws IOException
     */
    public static void respondWith401(String message) throws IOException {
        responseCodeAndMessage(HttpStatus.UNAUTHORIZED.value(),message);
    }

    /**
     * 响应 403
     * @param message
     * @throws IOException
     */
    public static void respondWith403(String message) throws IOException {
        responseCodeAndMessage(HttpStatus.FORBIDDEN.value(),message);
    }
}